package org.anyin.gitee.cloud.center.auth.extension.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.SecureUtil;
import lombok.extern.slf4j.Slf4j;
import org.anyin.gitee.cloud.center.auth.enums.AuthExCodeEnum;
import org.anyin.gitee.cloud.center.auth.enums.LoginTypeEnum;
import org.anyin.gitee.cloud.center.auth.enums.UserStatusEnum;
import org.anyin.gitee.cloud.center.auth.extension.LoginHandler;
import org.anyin.gitee.cloud.center.auth.extension.dto.LoginUserDTO;
import org.anyin.gitee.cloud.center.upms.api.SysUserFeignApi;
import org.anyin.gitee.cloud.center.upms.api.resp.SysUserResp;
import org.anyin.gitee.cloud.lib.core.web.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class UsernameLoginHandler implements LoginHandler {

    @Autowired
    private SysUserFeignApi sysUserFeignApi;

    @Override
    public LoginTypeEnum extension() {
        return LoginTypeEnum.USERNAME;
    }

    @Override
    public LoginUserDTO login(String... content) {
        // TODO param check
        String username = content[0];
        String password = content[1];

        SysUserResp sysUser = sysUserFeignApi.infoByUsername(username).getData();
        if(sysUser == null){
            throw AuthExCodeEnum.USER_NOT_REGISTER.getException();
        }
        // TODO add salt
        if(!sysUser.getPassword().equals(SecureUtil.md5(password))){
            throw AuthExCodeEnum.USER_PASSWORD_ERROR.getException();
        }
        if(UserStatusEnum.DISABLE.getCode().equals(sysUser.getStatus())){
            throw AuthExCodeEnum.USER_IS_DISABLE.getException();
        }
        sysUser.setPassword(null);

        StpUtil.login(sysUser.getId());
        SaTokenInfo token = StpUtil.getTokenInfo();

        LoginUserDTO user = new LoginUserDTO();
        user.setSysUser(sysUser);
        user.setToken(token);
        return user;
    }
}
